/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.example.netcracker.ui;

import java.awt.AWTException;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.util.Date;
import java.util.List;
import javax.swing.ImageIcon;
import ru.example.netcracker.controller.ControllerFacade;
import ru.example.netcracker.model.entity.Alarm;
import ru.example.netcracker.model.entity.Notification;
import ru.example.netcracker.model.observer.Observable;
import ru.example.netcracker.model.observer.Observer;
import ru.example.netcracker.model.entity.Task;
import ru.example.netcracker.timer.OnReceiveTaskListener;
import ru.example.netcracker.ui.TaskTable.DataTableModel;
import ru.example.netcracker.ui.listeners.OnClickTrayListener;
import ru.example.netcracker.ui.listeners.OnClickTableItemListener;

/**
 *
 * @author Nikolay
 */
public class MainFrame extends javax.swing.JFrame implements OnClickTableItemListener,
        OnClickTrayListener, OnReceiveTaskListener, Observer {

    public static MainFrame newInstance(ControllerFacade ctrl) {
        return new MainFrame(ctrl);
    }
    
    private AlarmDialog dialog;
    private ControllerFacade ctrl;

    public MainFrame(ControllerFacade ctrl) {
        initComponents();        
        this.ctrl = ctrl;
        
        dialog = AlarmDialog.newInstance(this, ctrl);
        dataTable.addOnClickTableItemListener(this);
        
        dataTable.setRows(ctrl.getTasks());
        dataTable.invalidate();

        clockPanel.setDateTime(new Date(System.currentTimeMillis()));
        clockPanel.startClock();

        if (!SystemTray.isSupported()) {
            System.out.println("SystemTray is not supported");
            return;
        }
        
        final TrayIcon trayIcon
                = new TrayIcon(new ImageIcon("resources/rocket.gif").getImage());

        final SystemTray tray = SystemTray.getSystemTray();

        SysTrayMenu menu = new SysTrayMenu();
        menu.addOnClickTrayListener(this);

        trayIcon.setPopupMenu(menu);
        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
        }
    }

    @Override
    public void update(Observable o, List<Task> tasks) {
        dataTable.setRows(tasks);
        dataTable.invalidate();
    }
    
    @Override
    public void onReceiveNotification(Notification notif) {
        if(!notif.isShow()) {
            notif.setShow(true);
            NotificationDialog.newInstance(this, ctrl, notif).setVisible(true);
        }
    }

    @Override
    public void onReceiveAlarm(Alarm alarm) {
        if(!alarm.isShow()) {
            alarm.setShow(true);
            ctrl.startPlayer(alarm.getPath());
            dialog.setAlarm(alarm);
            dialog.setVisible(true);
        }
    }

    @Override
    public void onClickChange(Task task) {
        CreateTaskDialog create = CreateTaskDialog.newInstance(this, ctrl);
        create.setTask(task);
        create.setVisible(true);      
    }

    @Override
    public void onClickDelete(Task task) {
        ctrl.deleteTask(task.getId());
    }

    @Override
    public void onClickOpen() {
        if (isVisible()) {
            setVisible(false);
        } else {
            setVisible(true);
        }
    }

    @Override
    public void onClickAdd() {
        CreateTaskDialog.newInstance(this, ctrl).setVisible(true);
    }

    @Override
    public void onClickPreferences() {
    }

    @Override
    public void onClickAbout() {
    }
    
    @Override
    public void onClickExit() {
        ctrl.close();
        System.exit(0);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        dataTable = new ru.example.netcracker.ui.TaskTable();
        clockPanel = new ru.example.netcracker.ui.ClockPanel();
        createButton = new javax.swing.JButton();
        changeButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();

        setResizable(false);

        jScrollPane1.setViewportView(dataTable);

        clockPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        createButton.setText("Создать");
        createButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createButtonActionPerformed(evt);
            }
        });

        changeButton.setText("Изменить");
        changeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeButtonActionPerformed(evt);
            }
        });

        deleteButton.setText("Удалить");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(clockPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(createButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(changeButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteButton)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(clockPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(createButton)
                    .addComponent(changeButton)
                    .addComponent(deleteButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void createButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createButtonActionPerformed
        CreateTaskDialog create = CreateTaskDialog.newInstance(this, ctrl);
        create.setVisible(true);
    }//GEN-LAST:event_createButtonActionPerformed

    private void changeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeButtonActionPerformed
        int idx = dataTable.getSelectedRow();
        DataTableModel model = (DataTableModel) dataTable.getModel();
        Task task = model.getRow(idx);
        CreateTaskDialog create = CreateTaskDialog.newInstance(this, ctrl);
        create.setTask(task);
        create.setVisible(true);
    }//GEN-LAST:event_changeButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        int idx = dataTable.getSelectedRow();
        DataTableModel model = (DataTableModel) dataTable.getModel();
        Task task = model.getRow(idx);
        ctrl.deleteTask(task.getId());
    }//GEN-LAST:event_deleteButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton changeButton;
    private ru.example.netcracker.ui.ClockPanel clockPanel;
    private javax.swing.JButton createButton;
    private ru.example.netcracker.ui.TaskTable dataTable;
    private javax.swing.JButton deleteButton;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
